import {
  reqCartList,
  reqUpdateChecked,
  reqUpdateAllChecked,
  reqAddOrUpdateCart,
  reqDeleteGoods
} from '../../api/index'
//购物车
Page({
  data: {
    goodsList: [], //购物车数据
    selectAll: false, //全选的状态
    totalPrice: 0, //总价
    totalNum: 0, //总个数
  },
  //生命周期函数-onLoad
  onShow() {
    //进入购物车判断是否登录
    const token = wx.getStorageSync('TOKEN');
    if (token) {
      //获取用户购物车
      this.getCartList();
    } else {
      wx.navigateTo({
        url: '/pages/login/login',
      })
    }

  },
  //封装一个函数,获取用户购物车的数据
  async getCartList() {
    const result = await reqCartList();
    if (result.code == 200) {
      this.setData({
        goodsList: result.data,
      });
      //计算全选
      this.setData({
        selectAll: this.computedAllChecked(),
        totalPrice: this.computedPrice(),
        totalNum: this.computedCount()
      })
    }
  },
  //计算属性值全选
  computedAllChecked() {
    return this.data.goodsList.every(item => item.isChecked == 1);
  },
  //计算总价
  computedPrice() {
    return this.data.goodsList.reduce((prev, goods) => {
      if (goods.isChecked == 1) {
        prev += goods.price * goods.count;
        return prev;
      }
      return prev;
    }, 0)
  },
  computedCount() {
    return this.data.goodsList.reduce((prev, goods) => {
      if (goods.isChecked == 1) {
        prev += goods.count;
        return prev;
      }
      return prev;
    }, 0)
  },
  //更新某一个商品的勾选状态
  async updateChecked(event) {
    const {
      goodsid
    } = event.currentTarget.dataset;
    const isChecked = event.detail ? 1 : 0;
    //更新商品勾选状态
    try {
      //更新成功
      await reqUpdateChecked(goodsid, isChecked);
      //获取更新后的购物车数据
      this.getCartList();
    } catch (error) {

    }
  },
  //更细全部商品的状态
  async updateAllChecked(event) {
    const isChecked = event.detail;
    //全部商品更新成功
    await reqUpdateAllChecked(isChecked ? 1 : 0);
    //再次获取购物车最新更新完毕的数据
    this.getCartList();
  },
  //更新商品的数量
  async updateCount(event){
    //更新商品的id
    const {goodsid,oldcount} = event.currentTarget.dataset;
    const newCount = event.detail - oldcount;
    //更新商品数量的请求
    await reqAddOrUpdateCart(goodsid,newCount);
    //再次获取更新后的购物车数据
    this.getCartList();
  },
  //删除某一个商品
  deleteGoods(event){
    const {goodsid} = event.currentTarget.dataset;
    //微信小程序内置模态框
    wx.showModal({
      title: event.currentTarget.dataset.name,
      complete: async(res) => {
        if (res.cancel) {
          
        }
    
        if (res.confirm) {
          //删除商品
           await reqDeleteGoods(goodsid)
           //获取更新后的购物车数据
           this.getCartList();
        }
      }
    })
  },
  //购物车页面结算按钮:进入订单页支付购物车全部商品
  goOrder(){
    wx.navigateTo({
      url: '/pages/order/order',
    })
  }
})